﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Aliyun.OSS;
using BlogApi.MyTool;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace BlogApi.Controllers
{
    [Route("api/image")]
    [ApiController]
    public class ImageController : ControllerBase
    {
        public ImageController()
        {

        }
        [HttpPost]
        [Route("uploadArticleImage")]
        [DisableRequestSizeLimit]
        public IActionResult UploadArticleImage(IFormFile file)
        {
            var host = "https://hatsune-miku-yyy-blog-static.oss-cn-chengdu.aliyuncs.com";
            var endpoint = "oss-cn-chengdu.aliyuncs.com";
            var accessKeyId = "LTAI4FdSL1CE3fznDt1JK6bY";
            var accessKeySecret = "GWZYP7S0Fjwv1gdcL72sb9gOAYw1PF";
            var bucketName = "hatsune-miku-yyy-blog-static";
            var objectName = "articleImages/" + Tools.GetTimeStamp() + Path.GetExtension(file.FileName);
            var localFilename = file;
            // 创建OssClient实例。
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            try
            {
                // 上传文件。
                var result = client.PutObject(bucketName, objectName, localFilename.OpenReadStream());
                Console.WriteLine("Put object succeeded");
                return new JsonResult(new
                {
                    status = "ok",
                    imageUrl = host + "/" + objectName
                });
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                Console.WriteLine("Put object failed, {0}", ex.Message);
            }
            return BadRequest();
#pragma warning restore CA1031 // Do not catch general exception types
        }
    }
}